package com.example.pre.business.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.pre.business.UserBusiness;
import com.example.pre.enums.UserTypeEnum;
import com.example.pre.exception.ServiceException;
import com.example.pre.model.Department;
import com.example.pre.model.User;
import com.example.pre.model.vo.UserVO;
import com.example.pre.service.DepartmentService;
import com.example.pre.service.UserService;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserBusinessImpl implements UserBusiness {

	@Autowired
	private UserService userService;
	@Autowired
	private DepartmentService departmentService;

	@Override
	public UserVO createUser(String name, String account, String sex, String password, int departmentId,
			UserTypeEnum type, String pic) throws Exception {

		Map<String, Object> selectMap = new HashMap<String, Object>();
		selectMap.put("account", account);
		Collection<User> users = userService.listByCondition(selectMap);
		if (CollectionUtils.isNotEmpty(users)) {
			throw new ServiceException("该账号已经存在;account=" + account, "用户已存在", -401);
		}
		Department department = departmentService.get(departmentId);
		if (department == null) {
			throw new ServiceException("部门不存在", "部门不存在", -404);
		}
		User user = new User();
		user.setName(name);
		user.setAccount(account);
		user.setDepartmentId(departmentId);
		user.setPassword(password);
		user.setPic(pic);
		user.setSex(sex);
		user.setType(type.name());

		userService.create(user);

		UserVO userVO = new UserVO(user, department.getName(), department.getDescription());
		return userVO;
	}

	@Override
	public UserVO getUser(int userId) throws Exception {
		User user = userService.get(userId);
		if (user == null) {
			return null;
		}
		Department department = departmentService.get(user.getDepartmentId());
		UserVO userVO = new UserVO(user, department.getName(), department.getDescription());
		return userVO;
	}

}
